package com.youlu.campus.service.form.impl;

import com.youlu.campus.entity.form.UserFormTaskDetailInfo;
import com.youlu.campus.service.form.UserFormTaskDetailInfoService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Objects;

@Slf4j
@Service
public class UserFormTaskDetailInfoServiceImpl implements UserFormTaskDetailInfoService {
    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public boolean update(UserFormTaskDetailInfo req) {
        Query query = new Query();
        query.addCriteria(Criteria.where("id").is(req.getId()));
        Update update = new Update();
        boolean toUpdate = false;
        if (StringUtils.isNotBlank(req.getUserFormTaskInfoId())) {
            update.set("userFormTaskInfoId", req.getUserFormTaskInfoId());
            toUpdate = true;
        }
        if (StringUtils.isNotBlank(req.getSingleFormQuestionId())) {
            update.set("singleFormQuestionId", req.getSingleFormQuestionId());
            toUpdate = true;
        }
        if (StringUtils.isNotBlank(req.getType())) {
            update.set("type", req.getType());
            toUpdate = true;
        }
        if (Objects.nonNull(req.getNo())) {
            update.set("no", req.getNo());
            toUpdate = true;
        }
        if (CollectionUtils.isNotEmpty(req.getDatas())) {
            update.set("datas", req.getDatas());
            toUpdate = true;
        }
        if (toUpdate) {
            update.set("updatedTime", new Date());
            return mongoTemplate.updateFirst(query, update, UserFormTaskDetailInfo.class).getModifiedCount() > 0 ? true : false;
        }
        return false;
    }

    @Override
    public UserFormTaskDetailInfo create(UserFormTaskDetailInfo req) {
        req.setId(null);
        if (Objects.nonNull(req.getCreatedTime())) {
            req.setCreatedTime(new Date());
        }
        return mongoTemplate.insert(req);
    }
}
